package com.canbot.u05.activity.customvoice;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.activity.customvoice.adapter.CustomDialogAdapter;
import com.canbot.u05.activity.customvoice.bean.CustomDialogData;
import com.canbot.u05.activity.customvoice.bean.CustomDialogExcelData;
import com.canbot.u05.activity.customvoice.bean.CustomDialogExcelDatas;
import com.canbot.u05.activity.customvoice.tool.CheckStringUtils;
import com.canbot.u05.activity.customvoice.tool.CommomDialog;
import com.canbot.u05.activity.customvoice.tool.CustomDialogExcelLoader;
import com.canbot.u05.activity.customvoice.tool.GridSpacingItemDecoration;
import com.canbot.u05.bean.AdvisoryQA;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.network.SalesApi;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * by liuheng
 * 自定义对话Excel导入
 **/
public class CustomDialogActivity extends BaseActivityNoTitle implements CustomDialogAdapter.OnItemClickListener {

        private static final String TAG = "CustomDialogActivity";

        private RecyclerView mRecyclerView;

        private CustomDialogAdapter mCustomDialogAdapter;

        private List<CustomDialogData> mCustomDialogData;

        private String filePath = Environment.getExternalStorageDirectory().toString() + File.separator;

        private String excelPath;

        private List<String> mQuestions = new ArrayList<>();

        private Dialog dialogLoading;

        private List<CustomDialogExcelData> mSameExcelData = new ArrayList<>();

        /**
         * 自动定义对话
         */
        private final int CUSTOM_DIALOG = 0;

        /**
         * 咨询问答
         */
        private final int SETTING_ADVISORY = 1;

        private int type;

        private RelativeLayout mRelativeLayout;

        private Handler mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                        switch (msg.what) {
                                case 1:
                                        data2View();
                                        break;
                                default:
                                        break;
                        }
                }
        };

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_custom_dialog);
                final Intent intent = getIntent();
                type = intent.getIntExtra("type", -1);
                mQuestions = JSON.parseArray(intent.getStringExtra("data"), String.class);

                initView();
        }

        private void initView() {

                mRecyclerView = findViewById(R.id.my_gridView);
                //网格布局，每行为4
                mRecyclerView.setLayoutManager(new GridLayoutManager(CustomDialogActivity.this, 4));
                mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(4, 120, false));
                mRelativeLayout = findViewById(R.id.relativeLayout1);
                mCustomDialogData = new ArrayList<>();
                getData();

                mCustomDialogAdapter = new CustomDialogAdapter(this, mCustomDialogData, this);

                mRecyclerView.setAdapter(mCustomDialogAdapter);

        }

        @Override
        public void onItemClick(View view) {
                final int i = (int) view.getTag();
                excelPath = mCustomDialogData.get(i).getPath();
                mCustomDialogAdapter.setChecked(i);
                mCustomDialogAdapter.notifyDataSetChanged();
        }

        private void data2View() {
                mCustomDialogAdapter.notifyDataSetChanged();
        }

        private void getData() {
                startGetThread();
        }

        private void startGetThread() {

                new MyThread().start();

        }


        public class MyThread extends Thread {

                @Override
                public void run() {
                        super.run();
                        doSearch(filePath);
                        final Message msg = new Message();
                        msg.what = 1;
                        msg.obj = 1;
                        mHandler.sendMessage(msg);

                }

                MyThread() {

                }
        }

        /****
         * 递归算法获取本地文件
         * @param path
         */
        private void doSearch(String path) {
                final File file = new File(path);

                if (file.exists()) {
                        if (file.isDirectory()) {
                                final File[] fileArray = file.listFiles();
                                for (File f : fileArray) {

                                        if (f.isDirectory()) {
                                                doSearch(f.getPath());
                                        }
                                        else {
                                                if (f.getName().endsWith(".xls")) {
                                                        try {
                                                                final CustomDialogData info = new CustomDialogData(f.getName(), f.getAbsolutePath(), false);
                                                                mCustomDialogData.add(info);
                                                                if (mCustomDialogData == null) {
                                                                        mRelativeLayout.setVerticalGravity(View.VISIBLE);
                                                                }
                                                        }
                                                        catch (Exception e) {
                                                                e.printStackTrace();
                                                        }
                                                }
                                        }
                                }
                        }
                }
        }

        public void updata(ArrayList<CustomDialogExcelDatas> customDialoglist) {

                mSameExcelData.clear();

                if (customDialoglist == null) {
                        ToastTools.newInstance(getApplicationContext()).showText(CustomDialogActivity.this.getString(R.string.table_data_empty));
                        return;
                }
                final ArrayList<CustomDialogExcelDatas> customDialoglists = checkString(removeSameAsDatas(removeSameData(customDialoglist)));

                Log.e(TAG, "------>" + customDialoglists);

                if (customDialoglists.size() > 0) {

                        if (type == CUSTOM_DIALOG) {
                                dialogLoading = LoadingDialogUtils.createLoadingDialog(CustomDialogActivity.this, getString(R.string.data_upload));
                                dialogLoading.show();

                                final int size = customDialoglists.size();

                                final String url = "http://" + IpMsgConst.SOCKET_HOST2 + ":7755/" + "dialogcustom";
                                final HashMap<String, Object> hashMap = new HashMap<>();
                                hashMap.put("chatCmdQsAsBean", JSON.toJSONString(customDialoglists));
                                hashMap.put("type", "6");
                                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                                        @Override
                                        public void onSuccess(String result) {
                                                dialogLoading.dismiss();
                                                final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);

                                                final String msg;

                                                if (strMsgBean.getRc() != 0) {
                                                        msg = strMsgBean.getMsg();
                                                }
                                                else {
                                                        runOnUiThread(new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                        ToastTools.newInstance(getApplicationContext()).showText(size + "条数据," + CustomDialogActivity.this.getString(R.string.upload_complete));
                                                                        if (mSameExcelData.size() > 0) {
                                                                                new CommomDialog(CustomDialogActivity.this, R.style.dialog, CustomDialogActivity.this.getString(R.string.upload_complete)
                                                                                        + size
                                                                                        + "条数据,"
                                                                                        + mSameExcelData.size()
                                                                                        + CustomDialogActivity.this.getString(R.string.upload_failed), true, "查看", new CommomDialog.OnCloseListener() {
                                                                                        @Override
                                                                                        public void onClick(Dialog dialog, boolean confirm) {
                                                                                                startActivity(new Intent(CustomDialogActivity.this, CustomDialogScreenActivity.class)
                                                                                                        .putExtra("samaData", JSON.toJSONString(mSameExcelData)));
                                                                                                finish();
                                                                                        }
                                                                                }).show();
                                                                        }
                                                                        else {
                                                                                finish();
                                                                        }
                                                                }
                                                        });
                                                }

                                        }

                                        @Override
                                        public void onFailure() {
                                                runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                                dialogLoading.dismiss();
                                                                ToastTools.newInstance(getApplicationContext()).showText(CustomDialogActivity.this.getString(R.string.upload_failed));
                                                        }
                                                });
                                        }
                                });
                        }
                        else if (type == SETTING_ADVISORY) {
                                {
                                        dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.data_upload));

                                        final int size = customDialoglists.size();

                                        final List<AdvisoryQA> advisoryQAList = new ArrayList<>();
                                        for (int i = 0; i < size; i++) {
                                                final AdvisoryQA advisoryQA = new AdvisoryQA();
                                                advisoryQA.setQuestion(customDialoglists.get(i).getListQsBean().get(0).getQuestion());
                                                advisoryQA.setAnswer(customDialoglists.get(i).getListAsBean().get(0).getTtstext());
                                                advisoryQA.setType(1);
                                                final String uuid = UUID.randomUUID().toString().replace("-", "");
                                                advisoryQA.setId(uuid);
                                                advisoryQAList.add(advisoryQA);
                                        }
                                        final Retrofit retrofit = new Retrofit.Builder()
                                                .baseUrl("http://" + IpMsgConst.SOCKET_HOST2 + ":7755")
                                                .addConverterFactory(GsonConverterFactory.create())
                                                .client(setTimeOut())
                                                .build();
                                        final SalesApi salesApi = retrofit.create(SalesApi.class);
                                        final String values = JSON.toJSONString(advisoryQAList);
                                        Logger.e(TAG, "上传数据" + values);
                                        Call<String> call = null;

                                        call = salesApi.addAdvisorys(values);

                                        call.enqueue(new Callback<String>() {
                                                @Override
                                                public void onResponse(Call<String> call, Response<String> response) {
                                                        if (response.body() != null) {
                                                                runOnUiThread(new Runnable() {
                                                                        @Override
                                                                        public void run() {
                                                                                ToastTools.newInstance(getApplicationContext()).showText(size + "条数据，上传成功！");
                                                                                if (mSameExcelData.size() > 0) {
                                                                                        new CommomDialog(CustomDialogActivity.this, R.style.dialog, CustomDialogActivity.this.getString(R.string.upload_complete)
                                                                                                + size
                                                                                                + "条数据,"
                                                                                                + mSameExcelData.size()
                                                                                                + CustomDialogActivity.this.getString(R.string.upload_failed), true, "查看", new CommomDialog.OnCloseListener() {
                                                                                                @Override
                                                                                                public void onClick(Dialog dialog, boolean confirm) {
                                                                                                        startActivity(new Intent(CustomDialogActivity.this, CustomDialogScreenActivity.class)
                                                                                                                .putExtra("samaData", JSON.toJSONString(mSameExcelData)));
                                                                                                        finish();
                                                                                                }
                                                                                        }).show();
                                                                                }
                                                                                else {
                                                                                        finish();
                                                                                }
                                                                        }
                                                                });
                                                        }
                                                        else {
                                                                LoadingDialogUtils.closeDialog(dialogLoading);
                                                        }
                                                }

                                                @Override
                                                public void onFailure(Call<String> call, Throwable t) {
                                                        LoadingDialogUtils.closeDialog(dialogLoading);
                                                        t.fillInStackTrace();
                                                        ToastTools.newInstance(getApplicationContext()).showText(CustomDialogActivity.this.getString(R.string.submit_failure));

                                                }
                                        });
                                }
                        }
                }
                else {
                        if (mSameExcelData.size() == customDialoglist.size() && mSameExcelData.size() > 0) {
                                ToastTools.newInstance(getApplicationContext()).showText("对话内容已导入成功，请勿重复提交！!");
                        }else {
                                ToastTools.newInstance(getApplicationContext()).showText(CustomDialogActivity.this.getString(R.string.table_data_empty));
                        }

                }

        }

        public void back(View view) {
                finish();
        }

        public void nextStep(View view) {
                if (mCustomDialogAdapter.getChecked() != -1) {
                        //导入Excel文档
                        new CustomDialogExcelLoader(this).execute(excelPath);
                }
                else {
                        ToastTools.newInstance(getApplicationContext()).showText(CustomDialogActivity.this.getString(R.string.please_select_dialogue_library));
                }
        }

        public void help(View view) {
                startActivity(new Intent(this, AddExcelHelpActivity.class));
        }

        private ArrayList<CustomDialogExcelDatas> removeSameData(ArrayList<CustomDialogExcelDatas> customDialogExcelData) {

                final ArrayList<CustomDialogExcelDatas> newArr = new ArrayList<>();

                boolean flag;
                for (int i = 0; i < customDialogExcelData.size(); i++) {
                        flag = false;
                        for (int j = 0; j < newArr.size(); j++) {
                                if (customDialogExcelData.get(i).getListQsBean().equals(newArr.get(j).getListQsBean())) {
                                        flag = true;
                                        break;
                                }
                        }
                        if (!flag) {
                                newArr.add(customDialogExcelData.get(i));
                        }
                        else {
                                final CustomDialogExcelData customDialogExcelData1 = new CustomDialogExcelData();
                                customDialogExcelData1.setQustion_str(customDialogExcelData.get(i).getListQsBean().get(0).getQuestion());
                                customDialogExcelData1.setTts_text(customDialogExcelData.get(i).getListAsBean().get(0).getTtstext());
                                mSameExcelData.add(customDialogExcelData1);
                        }
                }
                return removeSameAsDatas(newArr);
        }

        private ArrayList<CustomDialogExcelDatas> removeSameAsDatas(ArrayList<CustomDialogExcelDatas> customDialogExcelData) {

                if (mQuestions != null) {
                        final ArrayList<CustomDialogExcelDatas> newArr = new ArrayList<>();

                        for (int i = 0; i < mQuestions.size(); i++) {
                                for (int j = 0; j < customDialogExcelData.size(); j++) {
                                        if (mQuestions.get(i).equals(customDialogExcelData.get(j).getListQsBean().get(0).getQuestion())) {
                                                final CustomDialogExcelData customDialogExcelData1 = new CustomDialogExcelData();
                                                customDialogExcelData1.setQustion_str(customDialogExcelData.get(j).getListQsBean().get(0).getQuestion());
                                                customDialogExcelData1.setTts_text(customDialogExcelData.get(j).getListAsBean().get(0).getTtstext());
                                                mSameExcelData.add(customDialogExcelData1);
                                                newArr.add(customDialogExcelData.get(j));
                                        }
                                }
                        }

                        customDialogExcelData.removeAll(newArr);
                }
                return customDialogExcelData;
        }

        private ArrayList<CustomDialogExcelDatas> checkString(ArrayList<CustomDialogExcelDatas> customDialogExcelData) {

                final ArrayList<CustomDialogExcelDatas> newArr = new ArrayList<>();

                if (customDialogExcelData.size() > 0) {
                        for (int i = 0; i < customDialogExcelData.size(); i++) {
                                if (!CheckStringUtils.check(customDialogExcelData.get(i).getListQsBean().get(0).getQuestion()) || customDialogExcelData.get(i).getListQsBean().get(0).getQuestion().isEmpty()) {
                                        newArr.add(customDialogExcelData.get(i));
                                }
                        }
                        for (int i = 0; i < newArr.size(); i++) {
                                final CustomDialogExcelData customDialogExcelData1 = new CustomDialogExcelData();
                                customDialogExcelData1.setQustion_str(newArr.get(i).getListQsBean().get(0).getQuestion());
                                customDialogExcelData1.setTts_text(newArr.get(i).getListAsBean().get(0).getTtstext());
                                mSameExcelData.add(customDialogExcelData1);
                        }
                        customDialogExcelData.removeAll(newArr);
                }
                return customDialogExcelData;
        }

        /**
         * 超时时间100s
         */
        private static final int TIMEOUT = 100;

        /**
         * 设置超时
         *
         * @return
         */
        private OkHttpClient setTimeOut() {
                final OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .build();
                return client;

        }

        @Override
        protected void onDestroy() {
                // TODO Auto-generated method stub
                if (dialogLoading != null && dialogLoading.isShowing()) {
                        dialogLoading.dismiss();
                        dialogLoading = null;
                }
                super.onDestroy();
        }
}
